package com.sigmazero13.gameutils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sigmazero13.gameutils.GameImageService.LocalBinder;
import com.sigmazero13.gameutils.model.GameInfo;

public class GamePickerResult extends Activity {
	List<GameInfo> games;
	List<GameInfo> declined;
	GameInfo curGame;
	
	GameImageService mService;
	boolean mBound = false;
	
	Random r;
	
	TextView gameField;
	TextView ratingField;
	TextView lengthField;
	TextView playersField;
	ImageView gameImage;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.picker_result);
		Bundle bundle = getIntent().getExtras();
		Integer numPlayers = bundle.getInt("num_players");
		Integer maxLength = bundle.getInt("max_length");
		r = new Random();
		
		games = ((BoardGameUtilsApp)getApplication()).getDbHelper().selectMatchingGames(numPlayers, maxLength);
		declined = new ArrayList<GameInfo>();
		
		TextView numMatchesField = (TextView)this.findViewById(R.id.pick_result_num_matches);
		Resources res = getResources();
		String numMatchesStr = String.format(res.getString(R.string.random_num_matches), games.size());
		numMatchesField.setText(numMatchesStr);
		
		gameField = (TextView)this.findViewById(R.id.pick_result_game);
		ratingField = (TextView)this.findViewById(R.id.pick_result_rating);
		lengthField = (TextView)this.findViewById(R.id.pick_result_length);
		playersField = (TextView)this.findViewById(R.id.pick_result_players);
		gameImage = (ImageView)this.findViewById(R.id.pick_result_thumbnail);
		
		Button noButton = (Button)this.findViewById(R.id.pick_no);
		noButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				declined.add(curGame);
				curGame = null;
				pickRandomGame();
			}
		});
		
		Button yesButton = (Button)this.findViewById(R.id.pick_yes);
		yesButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.putExtra("game_id", curGame.getGameId());
				GamePickerResult.this.setResult(RESULT_OK, i);
				GamePickerResult.this.finish();
			}
		});
		
		pickRandomGame();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		Intent intent = new Intent(this, GameImageService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		unbindService(mConnection);
	}
	
	private void pickRandomGame() {
		if (games.size() == 0) {
			if (declined.size() == 0) {
				Toast.makeText(this, R.string.random_no_match, Toast.LENGTH_SHORT).show();
				finish();
				return;
			}
			
			games.addAll(declined);
			declined.clear();
			Toast.makeText(this, R.string.refresh_random_games, Toast.LENGTH_SHORT).show();
		}
		
		Integer weightTotal = 0;
		for (GameInfo game : games) {
			Double thisWeight = java.lang.Math.pow(game.getBggRating(), 1.75) * 100;
			weightTotal += thisWeight.intValue();
		}
		
		Integer random = r.nextInt(weightTotal);
		GameInfo game = null;
		weightTotal = 0;
		for (GameInfo thisGame : games) {
			Double thisWeight = java.lang.Math.pow(thisGame.getBggRating(), 1.75) * 100;
			weightTotal += thisWeight.intValue();
			
			if (random <= weightTotal) {
				game = thisGame;
				break;
			}
		}
		
		gameField.setText(game.getName());
		ratingField.setText(game.getBggRating().toString());
		lengthField.setText(game.getBggLength().toString() + " mins");
		playersField.setText(game.getNumPlayersString());
		gameImage.setImageDrawable(new BitmapDrawable());
		
		curGame = game;
		games.remove(game);
		
		getImage();
	}
	
	
	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			mBound = true;
			
			getImage();
		}
		
		@Override
		public void onServiceDisconnected(ComponentName className) {
			mBound = false;
		}
	};
	
	private void getImage() {
		new ImageTask().execute(curGame.getGameId());
	}
	
	private class ImageTask extends AsyncTask<Integer, Void, Drawable> {
		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected Drawable doInBackground(Integer... imageIds) {
			if (mBound) {
				return mService.getThumbnail(imageIds[0]);
			} else {
				return null;
			}
		}
		
		@Override
		protected void onPostExecute(Drawable result) {
			gameImage.setImageDrawable(result);
		}	
	}

}
